<template>
    <ul class="button-group">
        <Button v-for="item in newItems" :key="item.id" :isActive="item.isActive" @toggle-active="toggleActive(item.id)"
            class="button">
            <span>{{ item.name }}</span>
            <ul class="select" v-if="Array.isArray(item.children)">
                <Button v-for="i in item.children" :key="i.id" :isActive="i.isActive" @toggle-active="toggleActive(i.id)"
                    class="button-child">
                    <span>{{ i.name }}</span>
                </Button>
            </ul>
        </Button>
    </ul>
</template>
  
<script>
import Button from '@/components/Button.vue';

export default {
    name: 'ButtonGroup',
    components: {
        Button
    },
    props: {
        items: {
            type: Array
        },
        onChange: {
            type: Function
        }
    },
    data() {
        return {
            newItems: [],
            activeIndex: 0
        }
    },
    methods: {
        toggleActive(id) {
            this.setActive(this.newItems, id)
            this.$emit('onChange', { id })
        },
        setActive(arr, id) {
            arr.forEach(item => {
                if (item.id === id) {
                    this.$set(item, 'isActive', true)
                } else {
                    this.$set(item, 'isActive', false)
                }
                if (item.children) {
                    this.setActive(item.children, id)
                }
            });
        }
    },
    watch: {
        items() {
            if (this.items.length > 0) {
                this.newItems = JSON.parse(JSON.stringify(this.items))
                this.$set(this.newItems[0], 'isActive', true)
            }
        }
    }
}
</script>
  
<style lang="less" scoped>
.button-group {
    display: flex;
    width: fit-content;
    align-items: center;
    border: 1px solid #ccc;
    border-top: none;
    box-sizing: border-box;

    .button {
        flex: 1;

        &:hover {
            .select {
                max-height: 300px;
                visibility: visible;
            }
        }
    }

    .select {
        position: absolute;
        width: 100%;
        top: 48px;
        background-color: white;
        transition-property: max-height, visibility;
        transition-duration: .6s, 0s;
        border: 1px solid #ccc;
        border-top: none;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        max-height: 0;
        overflow: hidden;
        visibility: hidden;
    }

    span {
        line-height: 1.5rem;
    }

    .button-child:hover {
        color: blueviolet;
    }
}
</style>
  